package interview.volatiled;

import java.util.concurrent.atomic.AtomicInteger;

/**
 *   volatile不保证原子性解决
 *
 *   1、加上synchronized
 *   2、AtomicInteger
 *
 *
 * */
class Resource4{

    public   AtomicInteger atomicInteger=new AtomicInteger();

    public   void add(){
     /*   try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/

        atomicInteger.getAndIncrement();
    }
}

public class VolatileDemo4 {

    public static void main(String[] args) {
        Resource4 resource = new Resource4();

        for(int i=0;i<20;i++){

            new Thread(()->{
                System.out.println(Thread.currentThread().getName());
                for(int j=0;j<100;j++){
                    resource.add();
                }

            },String.valueOf(i)).start();

        }
        while (Thread.activeCount()>2){
            Thread.yield();
        }
        System.out.println("number="+resource.atomicInteger);
    }


}
